import cv2
import numpy as np

def remove_lines_and_fill(image_path, bg_color=(255, 255, 255)):
    # 读取图像
    img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

    # 使用Canny算法检测边缘
    edges = cv2.Canny(img, threshold1=100, threshold2=200)

    # 寻找轮廓
    contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 创建一个与原图同样大小的全背景色图像
    filled_img = np.full(img.shape, bg_color[0], dtype=np.uint8).astype(np.uint8)
    filled_img = cv2.cvtColor(filled_img, cv2.COLOR_GRAY2BGR)  # 若原图为彩色图像，创建彩色背景

    # 遍历轮廓，对轮廓内的区域填充背景色
    for contour in contours:
        x, y, w, h = cv2.boundingRect(contour)
        filled_img[y:y+h, x:x+w] = bg_color

    return filled_img

# 使用函数
image_without_lines = remove_lines_and_fill('test4.jpg')
cv2.imwrite('output_image.jpg', image_without_lines)